import base64
import os
import re
import time
from datetime import datetime
import json
import urllib.request
from flask import (
    jsonify,
    Blueprint
)
from pymongo import DESCENDING
from config.config import debug, host_name
import logging

from app import Log
from app.response import ResponseError
from app.routes import Route
from app.routes.websocket_route import socketIo, namespace, add_one_message, docker_cmd
from app.session import redis
from config.config import Base, redisIp, redisPort, QCloud
from model.mysql.tao.PushMessageDelay import PushMessageDelay
from model.weather.city_code import city_code_info
from service import redis_service, mongo_service, WAY_POINT, third_service, ThirdService, mongo_book
from util.date.nongli import get_ludar_date, lunar_month, lunar_day
from util.lib.BaseUtil import Util
from util.mysql.MysqlTable import MysqlTable
from redis import Redis

name = 'mtk'
mtk_route = Blueprint(name, __name__, template_folder=Base.templateUrl)
logger = Log(name).init()
route = Route(name)
try_catch = route.mtk_wrapper


# # logger = logging.getLogger(name)
# # print(host_name)
# file_name = os.path.join(os.path.split(os.path.realpath(__file__))[0], '../logs',
#                          str(name) + "_" + str(host_name)[:-1] + '.log')
# # if not os.path.exists(file_name):
# #     open(file_name, 'w')
# #
# # handler = logging.FileHandler(file_name, encoding='UTF-8')
# # log_format = logging.Formatter(
# #     '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')
# # handler.setFormatter(log_format)


@mtk_route.route('/getMethods', methods=["GET"])
@try_catch
def get_methods(data):
    return jsonify({
        'err': 0,
        'msg': redis_service.session.get(Route.get_router_saver_key(name))
    })


@mtk_route.route('/get_time', methods=["GET"])
@try_catch
def get_time(data):
    device_id = data[2]
    cmd = data[3]
    # {T*MTKWATCH*358688000039858*get_time}
    # {get_time#358688000039858#1530163424}
    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            cmd,
            time.time()
        ]
    })


weather = (
    '冰雹',  # 0
    '多云',  # 1
    '风',  # 2
    '晴',  # 3
    '沙尘',  # 4
    '雾霾',  # 5
    '雪',  # 6
    '阴',  # 7
    '雨'  # 8
)

weather_ff = {
    '晴': 3,
    '多云': 1,
    '阴': 7,
    '阵雨': 8,
    '雷阵雨': 8,
    '雷阵雨伴有冰雹': 0,
    '雨夹雪': 6,
    '小雨': 8,
    '中雨': 8,
    '大雨': 8,
    '暴雨': 8,
    '大暴雨': 8,
    '特大暴雨': 8,
    '阵雪': 6,
    '小雪': 6,
    '中雪': 6,
    '大雪': 6,
    '暴雪': 6,
    '雾': 5,
    '冻雨': 8,
    '浮尘': 4,
    '扬沙': 4,
    '沙尘暴': 4,
    '霾': 5
}


@mtk_route.route('/get_city_status', methods=["GET"])
@try_catch
def get_city_status(data):
    device_id = data[2]
    cmd = data[3]
    # {T*MTKWATCH*358688000039858*get_city_status*460*1*9493*47572} 460,1,9493,47572,63
    # {358688000039858#get_city_status#深圳#晴天#大年初一#16(最低温度)#26(最高温度)}
    logger.debug('adfadfadfadsfad')
    url = 'http://api.cellocation.com:81/cell/?mcc=' + data[4] + \
          '&mnc=' + data[5] + \
          '&lac=' + data[6] + '&ci=' + data[7] + '&output=json'
    logger.info(url)
    res = third_service.json_get(url)

    # logger.info(res)
    address = res['address']
    city = ''
    for char in address:

        city += char
        if char == '省':
            city = ''
        elif char == '市':
            break

    if not city:
        return jsonify({
            'err': 1,
        })

    city = city[:-1]

    url = 'http://t.weather.sojson.com/api/weather/city/' + city_code_info[city]
    res = third_service.json_get(url)
    data_arr = Util.get_key(['data', 'forecast'], res)
    if not data_arr:
        return jsonify({
            'err': 1,
        })

    data = data_arr[0]


    find_float = lambda x: re.search("\d+(\.\d+)?", x).group()

    now = datetime.now()
    (year, month, day) = get_ludar_date(datetime(now.year, now.month, now.day))
    _type = weather_ff[data.get('type')]
    if not type:
        _type = 3

    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            cmd,
            city,
            _type + 1,
            lunar_month(month) + lunar_day(day),
            find_float(data.get('low')),
            find_float(data.get('high')),
        ]
    })


@mtk_route.route('/get_qrcode', methods=["GET"])
@try_catch
def get_qrcode(data):
    device_id = data[2]

    url = 'http://qr.liantu.com/api.php?text={"deviceId": "' + device_id + '", "type": "p9"}'
    logger.info(url)
    req = urllib.request.Request(url)
    response = urllib.request.urlopen(req, timeout=3)
    res_bytes = response.read()
    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            'get_qrcode',
            base64.encodebytes(res_bytes).decode(encoding='utf-8')
        ]
    })


@mtk_route.route('/get_friends', methods=["GET"])
@try_catch
def get_friends(data):
    device_id = data[2]
    family_obj = mongo_service.find_one('family', {
        'sn': device_id
    })

    _str = ''
    if family_obj:
        del family_obj['sn']
        del family_obj['_id']
        has = False
        for key in family_obj:
            has = True
            _str += "%s,%s,%s|" % (key, family_obj[key]['nick_name'], family_obj[key]['phone'])
        if has:
            _str = _str[:-1]

    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            'get_friends',
            _str
        ]
    })


#  ["T","MTKWATCH","358698789854873","send_message","MTM0NTY2NzkA","1","oYsiN0XhDHacr1DTNenM69TuEwX8","1545127658"]
@mtk_route.route('/send_message', methods=["GET"])
@try_catch
def send_message(data):
    device_id = data[2]
    content = data[4]
    obj_type = data[5]
    obj_number = data[6]
    timestamp = data[7]

    print(device_id, content, obj_type, obj_number)

    if len(obj_number) < 22:
        # todo 根据device_id 找 ctl
        device_info = mongo_service.find_one('devices', {
            'sn': device_id
        })
        ctl = device_info.get('ctl', '')
        if not ctl:
            return jsonify({
                'err': 1
            })
        else:
            obj_number = ctl

    sid = redis.hget(obj_number, 'sid')
    if not sid:
        raise BaseException('no online')
    sid = sid.decode()

    content = base64.decodebytes(content.encode(encoding='utf-8')).decode()
    msg_content = {"content": content, "sender": device_id, "time": int(timestamp), "type": "0"}

    add_one_message(device_id, obj_number, content)
    socketIo.emit('self_message', msg_content, sid, namespace=namespace)
    # socketIo.emit('test', "dfadfdasfads", sid, namespace=namespace)
    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            'send_message_ack',
            0
        ]
    })


# 008796751233306
@mtk_route.route('/get_friend', methods=["GET"])
@try_catch
def get_friend(data):
    device_id = data[2]
    family_obj = mongo_service.find_one('family', {
        'sn': device_id
    })

    _str = ''
    if family_obj:
        del family_obj['sn']
        del family_obj['_id']
        has = False
        for key in family_obj:
            has = True
            info = mongo_service.find_one('users', {
                "openid": key
            })
            nickname = info.get('nickname', '')
            _str += "%s,%s,%s|" % (key, nickname, family_obj[key]['phone'])
        if has:
            _str = _str[:-1]

    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            'get_friends',
            _str
        ]
    })


@mtk_route.route('/get_category', methods=["GET"])
@try_catch
def get_category(data):
    device_id = data[2]
    cmd = data[3]

    redis = Redis(redisIp, redisPort)
    categories = redis.hgetall('tao.category')

    content = ''
    for category_id in categories:
        category_name = categories[category_id]
        content += category_id.decode() + ',' + category_name.decode() + '|'
    content = content[:-1]

    # {T*MTKWATCH*358688000039858*get_category}
    # {358688000039858#get_category#category_id1,name1|category_id2,name2|category_id3,name3|category_id4,name4|category_id5,name5}
    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            cmd,
            content
        ]
    })


@mtk_route.route('/get_books', methods=["GET"])
@try_catch
def get_books(data):
    device_id = data[2]
    category_id = data[4]
    book_id = data[5]
    limit = int(data[6])
    # {T*MTKWATCH*358688000039858*get_books*category_id1*book_id(默认为空串)*10(limit)}
    # {get_books#358688000039858#book_id1,name1,path|book_id2,name2,path|book_id3,name3,path}
    redis = Redis(redisIp, redisPort)
    category_name = redis.hget('tao.category', category_id).decode()

    content = ''
    if not book_id:
        print(category_name)
        obj_arr = mongo_book.select_colum('books', {"majorCate": category_name}, {
            'title': 1
        }).sort([("_id", DESCENDING)]).limit(limit)
        # obj_arr = mongo_book.select_colum('books', {"majorCate": category_name}, {
        #     'title': 1
        # }).limit(limit)

        for item in obj_arr:
            print(item)
            content += item.get('_id') + ',' + item.get('title') + ',/mongo/' + item.get('_id') + '|'
    content = content[:-1]

    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            data[3],
            content
        ]
    })


@mtk_route.route('/location_cell', methods=["GET"])
@try_catch
def location_cell(data):
    device_id = data[2]
    cmd = data[3]
    # {T*MTKWATCH*358688000039858*get_city_status*460*1*4301*20986*wgs84}
    # {358688000039858#location_cell}
    category_id = data[4]
    book_id = data[5]
    limit = data[6]
    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            cmd
        ]
    })


@mtk_route.route('/wifi', methods=["GET"])
@try_catch
def wifi(data):
    device_id = data[2]
    cmd = data[3]
    data = data[4]
    # '{T*MTKWATCH*358688000039867*wifi*2*c8:3a:35:15:71:38,-84,Tenda_157138|70:3a:d8:11:78:60,-86,WXlmjd}'
    #     data = data.strip()
    # {358688000039858#location_wifi}

    # data_arr = data.split('|')
    # mac_arr = []
    # for item in data_arr:
    #     item_arr = item.split(',')
    #     mac_arr.append(item_arr[0])
    # new_data_arr.append(item_arr[0] + ',' + item_arr[1])
    # http://api.cellocation.com:81/wifi/?mac=30:fc:68:72:d:4a&output=json

    # for mac in mac_arr:
    #     url = 'http://api.cellocation.com:81/wifi/?mac=' + mac + '&output=json'
    #     res = third_service.json_get(url)
    #
    #     if 'errcode' in res and res['errcode'] == 0:
    #         logger.info("XXXXXXXXXX=" + json.dumps(res))
    #         way_point(device_id, res['lat'], res['lon'], 0, 0, res['radius'], res['address'])
    #         break

    # http://api.cellocation.com:81/loc/?output=json&cl=460,0,9784,4596,37;460,0,9784,4616,31&wl=c:4b:54:9b:8e:47,-72;28:2c:b2:50:74:30,-89;78:44:fd:44:cd:6,-90;b0:95:8e:2a:41:21,-93;c8:8d:83:9f:66:bc,-52;c8:8d:83:9f:66:bd,-47

    url = 'http://api.cellocation.com:81/loc/?output=json&' + data
    logger.info("device_id=" + device_id + "||||||wifi_url=" + url)
    res = third_service.json_get(url)
    if 'errcode' in res and res['errcode'] == 0:
        logger.info("XXOOOOOOOOOOOXX=" + json.dumps(res))
        way_point(device_id, res['lat'], res['lon'], 0, 0, res['radius'], res['address'])

    return jsonify({
        'err': 0,
        'msg': [
            device_id,
            'wifi_act',
            0
        ]
    })

    # {T*MTKWATCH*358688000039858*make_qcode}
    # {358688000039858#make_qcode#iasdjfaiekeifa}


@mtk_route.route('/get_txt', methods=["GET"])
@try_catch
def get_txt(data):
    device_id = data[2]
    cmd = data[3]
    path = data[4]
    # index = int(data[5])
    root = "/home/mtk_data/book"

    # if path[:6] == '/mongo':
    book_id = path.split('/')[2]
    print('book_id', book_id, path[:6])

    url = "http://weixin.pbani.com/test.txt"

    return jsonify({
        'err': 0,
        # 'chunk': 1,
        'msg': [
            device_id, 'get_txt', path, url
        ]
    })

    # real_path = root + path
    #
    # logger.debug(real_path)
    #
    # if not os.path.exists(real_path):
    #     return jsonify({
    #         'err': 1,
    #         'msg': 'no file'
    #     })
    #
    # content = ''
    # with open(real_path, 'r', encoding='utf-8') as file:
    #     for line in file:
    #         content += line
    #
    # logger.debug(content)
    #
    # base64_bytes = base64.b64encode(content.encode(encoding='utf-8'))
    # base64_s = base64_bytes.decode()
    #
    # num = 800
    # _arr = range(0, len(base64_s), num)
    # _arr_length = len(_arr)
    # # arr = [
    # #     [
    # #         cmd,
    # #         device_id,
    # #         int(time.time()),
    # #         i,
    # #         _arr_length,
    # #         base64_s[i:i + num]
    # #     ]
    # #     for i in _arr
    # # ]
    #
    # # {T*MTKWATCH*358688000039858*getTxt*/test}
    # # {getTxt358688000039858#1520909393#0#9#iasdjfaiekeifa}
    # return jsonify({
    #     'err': 0,
    #     # 'chunk': 1,
    #     'msg': [
    #         device_id, 'get_txt', index, _arr_length, base64_s[index * num:index * num + num]
    #     ]
    # })


@mtk_route.route('/newlocation', methods=["GET"])
@try_catch
def newlocation(data):
    device_id = data[2]
    elc = data[4]

    # todo save elc

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'LOWBATTERY_ACT', int(time.time())
        ]
    })


@mtk_route.route('/lowbattery', methods=["GET"])
@try_catch
def lowbattery(data):
    device_id = data[2]
    elc = data[4]

    # todo save elc

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'LOWBATTERY_ACT', int(time.time())
        ]
    })


@mtk_route.route('/getvoice', methods=["GET"])
@try_catch
def getvoice(data):
    device_id = data[2]
    file_name = data[4]

    obj = mongo_service.find_one('file', {
        'file_name': file_name
    })
    if not obj:
        raise BaseException('error file name')
    url = obj.get('url', '')
    if not url:
        raise BaseException('error url')

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'VOICE', file_name, url
        ]
    })


# http://tao-1251758307.file.myqcloud.com/wx/977777777777774-1542912120.mp3
# 28
# post_template_of_unread_message post_template_of_unread_message post_template_of_unread_message
# {"touser": "oYsiN0ca9clf-4a0g6UTdLodmt20", "template_id": "tp80iNSBFsTPObqK1NJ2zN3CxcTSMUZLnmLjSXt4rhY", "url": "http://weixin.pbani.com/wx/index?action=record&device_id=977777777777774", "data": {"first": {"value": "\u60a8\u597d\uff0c\u60a8\u5173\u6ce8\u7684\u8bbe\u5907", "color": "#173177"}, "keyword1": {"value": "P8-7", "color": "#173177"}, "keyword2": {"value": "2018-11-22 18:43:01", "color": "#173177"}, "keyword3": {"value": "\u672a\u8bfb\u6d88\u606f\u63d0\u9192", "color": "#173177"}, "remark": {"value": "\u5df2\u5411\u60a8\u53d1\u9001\u6d88\u606f\uff0c\u8bf7\u6ce8\u610f\u67e5\u770b", "color": "#173177"}}}
# <Response [200]>
# test-- {'errcode': 0, 'errmsg': 'ok', 'msgid': 558532163331522560}
# sid=e7e06b9a74f0451d8232b9b73b15a1c6
# {'content': 'http://tao-1251758307.file.myqcloud.com/wx/977777777777774-1542912120.mp3', 'sender': '977777777777774', 'time': '1542912120', 'type': 2}
# 118.24.98.157 - - [22/Nov/2018 10:43:02] "GET /mtk/voice?r=T%2AMTKWATCH%2A977777777777774%2Avoice%2AVXQ9iwgNQeB1mjaYzpoPlngBV4f3Nb2CNiAUUrEgPDRff332VAuB4SjL%2BsTzLkj0EO8e%2FP0azVLJGjvhqSA8MENnNATeiUHgfetUMHI8f9Uq2xf9tg27pKoVrWaDYDw6XmdNeHgSwce9qoGPk77sc8s0bLqU%2BVvwmFainBowPDJCXT9ENhCh4QUb%2BJP%2FCGqpXvhwCUGecY52Mb0pqmA8OlV%2FRDxsGyHg16v0bH0OolNXXHK2a7DHQwJQ%2BBCXQDw4XmEi4wSQIeFjunTZXCQ4B7FcIzfGWflyziTkTanQPEJDX5f4GIYB4GGIhzxspBr8v30nuKdjCQHnbPWHuoA8LltxJ9O%2BCSDweLerF2p1NPizjQUjn%2BQiAq%2B8YMBBgDw0QmSPVSAcIeHc6mprIsnzY72zFaFSk43abqEAXyaAPEBefzWQFjLB4cp7Y3CCA2Ge6pI9NgDkAUxzZgD2OaA8NFQkggTAEkHgoNiIWDYN2yNGy8sanb7cX4GoYlvwADw4QF8g61QDQeB4K0RKoNtwLnFpeapx2snQqQFnYQMQPDpUJE%2FuRIUh4HqKmiwEqs9iS008164mEwX%2FuesdDoA8KF5nRBkGCYGk3ej%2FzTQiF%2F%2FG9FORNGsRoqUOVJVfoDxGXF0y6aYDQNL1WG3leBchbKujxtRDGNZcgIklAwMAPCg%2FY4vl3AlhaYyab8RVJOdpjOnnMZ6m43bI5Pl%2FN9A8Qvx9mmMgTknnnPiCq8IO%2FOb6K8nOLXqwMnd4IEm9MA%3D%3D%2A11%2A12%2A0%2AoYsiN0ca9clf-4a0g6UTdLodmt20%2A1542912120%2A1 HTTP/1.1" 200 270 1.125608
# (3895) accepted ('172.17.0.1', 46124)
# (3895) accepted ('172.17.0.1', 46130)


@mtk_route.route('/voice', methods=["GET"])
@try_catch
def voice(data):
    print("CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC")
    logger.info("dfghjkl")
    device_id = data[2]
    base64_str = data[4]
    index = data[5]
    total_index = int(data[6])
    obj_type = data[7]
    obj_number = data[8]
    # if len(data) > 9:
    #     timestamp = data[9]
    # else:
    #     timestamp = int(time.time() * 1000)
    timestamp = data[9]
    voice_type = int(data[10])  # 0 正常语聊 1 监听

    file_name = device_id + '-' + str(timestamp)

    redis.setex("voice-" + file_name + "-" + str(index), base64_str, 300)
    redis.incr("voice-" + file_name + "-total_index")
    now_total_index = int(redis.get("voice-" + file_name + "-total_index"))
    print('now_total_index: ' + str(now_total_index))

    if now_total_index >= total_index:
        print("full~~~~~~~~~~~~~~~~~~~~~~~~~~~s")
        redis.delete("voice-" + file_name + "-total_index")
        content = ''
        for index in range(total_index):
            key = "voice-" + file_name + "-" + str(index)
            content += redis.get(key).decode()
            redis.delete(key)
        if not content:
            raise BaseException('error content')
        print(content)
        tmp_true_content = base64.decodebytes(content.encode(encoding='utf-8'))

        amr_file_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], '../temp', file_name + '.amr')
        mp3_file_path = os.path.join(os.path.split(os.path.realpath(__file__))[0], '../temp', file_name + '.mp3')

        file = open(amr_file_path, "wb")
        file.write(tmp_true_content)
        file.close()

        cmd = "docker run -v /var/www/:/var/www jrottenberg/ffmpeg -i " + amr_file_path + " " + mp3_file_path
        docker_cmd(cmd)

        bucket = third_service.cos.get_bucket(QCloud.get('bucket'))
        push_res = bucket.upload_file(
            real_file_path=mp3_file_path,
            file_name=file_name + '.mp3', dir_name=QCloud.get('dir'))
        url = json.loads(push_res.replace("'", '"'))['access_url']
        print(url)
        mongo_service.insert('file', {
            'file_name': file_name,
            'url': url
        })

        msg_type = 1
        if voice_type == 1:
            msg_type = 2

        add_one_message(device_id, obj_number, url, msg_type)

        sid = redis.hget(obj_number, 'sid')
        if sid:
            sid = sid.decode()
            print("sid=" + sid)
            msg_content = {"content": url, "sender": device_id, "time": timestamp, "type": msg_type}
            if voice_type == 1:
                socketIo.emit('upload_voice_msg', url, sid, namespace=namespace)
            print(msg_content)
            socketIo.emit('self_message', msg_content, sid, namespace=namespace)

        return jsonify({
            'err': 0,
            'msg': [
                device_id, 'VOICE_ACT', timestamp, url
            ]
        })

    return jsonify({
        'err': 0
    })


begin_time = 10
add_time_exp = 300
LOGIN_DELAY_PUSH_TIME = '2037-10-10 10:10:10'


# content_type (0:voice 1:text)
def push(device_id, device_type, number, content_type, content):
    print(device_id + " push to " + number + " " + str(content_type) + '||||' + content)
    redis = Redis(redisIp, redisPort)
    pc_info = redis.hget('tao.online', number)

    now = int(time.time())
    cmd = 'push'

    push_message_delay = MysqlTable('tao', 'push_message_delay')
    if pc_info:
        pc_info = pc_info.decode()
        print(number + " is online")
        push_message_delay.add_one({
            PushMessageDelay.CMD: cmd,
            PushMessageDelay.TIME_BEGIN: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now + begin_time)),
            PushMessageDelay.TIME_EXP: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now + add_time_exp)),
            PushMessageDelay.FROM: 'service',
            PushMessageDelay.TO: number,
            PushMessageDelay.DATA: json.dumps([device_id, device_type, number, content_type, content]),
            PushMessageDelay.DATA_FLAG: now
        })
        push_message_delay.conn.commit()
        mid = push_message_delay.last_insert_id()
        arr = pc_info.split(':')

        url = 'http://118.24.98.157:1' + arr[1] + '/push'
        print("mtk service url:" + url)
        req = urllib.request.Request(url)

        try:
            response = urllib.request.urlopen(
                req,
                '&'.join(map(str, [mid, device_id, device_type, number, content_type, content])).encode(
                    encoding='utf-8'),
                timeout=1
            )
        except Exception as e:
            print(e)
        # res_str = response.read().decode('utf-8')
        # json_obj = json.loads(res_str)
        # print(json_obj)
    else:
        print(number + " is not online")
        push_message_delay.add_one({
            PushMessageDelay.CMD: cmd,
            PushMessageDelay.TIME_BEGIN: LOGIN_DELAY_PUSH_TIME,
            PushMessageDelay.TIME_EXP: LOGIN_DELAY_PUSH_TIME,
            PushMessageDelay.FROM: 'service',
            PushMessageDelay.TO: number,
            PushMessageDelay.DATA: json.dumps([device_id, device_type, number, content_type, content]),
            PushMessageDelay.DATA_FLAG: now
        })
        push_message_delay.conn.commit()

    push_message_delay.close()
    push_message_delay.conn.close()


@mtk_route.route('/VOICE_ACT', methods=["GET"])
@try_catch
def VOICE_ACT(data):
    device_id = data[2]
    cmd = data[3]

    return jsonify({
        'err': 0,
        'msg': [
            device_id, cmd, 0
        ]
    })


@mtk_route.route('/LBS', methods=["GET"])
@try_catch
def LBS(data):
    device_id = data[2]

    content = data[4]
    elc = data[5]
    get_arr = {}
    for key_value in content.split('&'):
        arr = key_value.split('=')
        if len(arr) == 2:
            get_arr.setdefault(arr[0], arr[1])

    print(get_arr)
    url = 'http://api.cellocation.com:81/loc/?cl=' + get_arr['bts'] + '&output=json'
    print(url)
    res = third_service.json_get(url)

    print(res)
    if res['lat']:
        way_point(device_id, res['lat'], res['lon'], 0, elc, res['radius'], res['address'])

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'LBS_ACT', 0
        ]
    })


def way_point(device_id, lat, lon, _type, elc, radius=-1, address=''):
    print({
        'sn': device_id,
        'utc': datetime.now(),
        'serverTime': int(time.time()),
        'point': [
            float(lat),
            float(lon),
        ],
        'type': _type,
        'elc': int(elc),
        'radius': int(radius),
        'address': address,
    })
    res = mongo_service.insert(WAY_POINT, {
        'sn': device_id,
        'utc': datetime.now(),
        'serverTime': int(time.time()),
        'point': [
            float(lat),
            float(lon),
        ],
        'type': _type,
        'elc': int(elc),
        'radius': int(radius),
        'address': address,
    })
    print("TTTTTTTTTTTTTTTTTTTTTTTTT")
    print(res)


@mtk_route.route('/GPS', methods=["GET"])
@try_catch
def GPS(data):
    device_id = data[2]
    lat = data[4]
    lon = data[5]
    elc = data[6]

    way_point(device_id, lat, lon, 0, elc)

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'GPS_ACT', 0
        ]
    })


@mtk_route.route('/heartbeat', methods=["GET"])
@try_catch
def heartbeat(data):
    device_id = data[2]
    elc = data[4]  # 百分比
    # todo 保存elc
    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'heartbeat', 0
        ]
    })


@mtk_route.route('/login', methods=["GET"])
@try_catch
def login(data):
    device_id = data[2]
    if not device_id:
        raise ResponseError('no device id')

    device_info_arr = list(mongo_service.select_colum('devices', {
        'sn': device_id
    }, {
                                                          'sn': 1
                                                      }))

    logger.info(device_id)

    if len(device_info_arr) == 0:
        raise ResponseError('no device obj')

    redis = Redis(redisIp, redisPort)

    redis.hset("tao.online", device_id, "118.24.98.157:9500")

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'login', 0
        ]
    })


@mtk_route.route('/please_call_listen', methods=["GET"])
@try_catch
def please_call_listen(data):
    device_id = data[2]
    if not device_id:
        raise ResponseError('no device id')

    obj_device_id = data[4]

    ThirdService.inner_service(obj_device_id, 'newcalllisten', [
        obj_device_id,
        '15889297972',
    ])

    return jsonify({
        'err': 0,
        'msg': [
            device_id, 'please_call_listen', 0
        ]
    })
